package com.yuwen.yuwenRPC.fault;

/**
 * @ClassNameExponentialBackoffRetryStrategy
 * @Description TODO
 * @Author钰玟
 * @Date2025/4/6 下午1:07
 * @Version 1.0
 **/


import com.github.rholder.retry.*;
import com.yuwen.yuwenRPC.model.RpcResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * 指数退避算法 重试机制
 */
@Slf4j
public class ExponentialBackoffRetryStrategy implements RetryStrategy {


    /**
     * 指数退避重试机制
     * @param callable
     * @return
     * @throws Exception
     */
    @Override
    public RpcResponse doRetry(Callable<RpcResponse> callable) throws Exception {
        Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder()
                .retryIfExceptionOfType(Exception.class)
                .withWaitStrategy(WaitStrategies.exponentialWait(1l,10l, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(5))
                .withRetryListener(new RetryListener() {
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
                        log.info("重试次数，{}", attempt.getAttemptNumber());
                    }
                }).build();
        return retryer.call(callable);
    }
}
